import { onActivated } from 'vue'
import { useRoute } from 'vue-router'
interface pathsWithKeysType {
  key: string
  path: string
}
export function useActivated(
  initParams: Record<string, any>,
  context: any,
  pathsWithKeys: pathsWithKeysType[],
  fetchData: (newParams?: object | undefined) => void,
  excludedQueryKeys: Array<string>
) {
  const route = useRoute()
  const previousParams: Record<string, any> = { ...initParams }
  // 解析路径并获取响应式引用的值
  function getValuesByCustomKeys(context: any, pathsWithKeys: pathsWithKeysType[]) {
    return pathsWithKeys.reduce((acc: Record<string, any>, { key, path }) => {
      const value = path.split('.').reduce((acc, part) => acc[part], context)
      acc[key] = value
      return acc
    }, {})
  }
  function paramsChanged(previousParams: Record<string, any>, combinedParams: Record<string, any>) {
    // console.log('previousParams:', previousParams)
    // console.log('combinedParams:', combinedParams)
    const allKeys = new Set([...Object.keys(previousParams), ...Object.keys(combinedParams)])
    for (const key of allKeys) {
      if (previousParams[key] != combinedParams[key]) {
        console.log('key:', key)
        console.log('previousParams[key]:', previousParams[key])
        console.log('combinedParams[key]:', combinedParams[key])
        return true // 发现不匹配的值，表示参数发生了变化
      }
    }
    return false // 所有比较的值都匹配，表示参数没有变化
  }
  onActivated(() => {
    // 过滤不需要的查询参数
    const filteredQuery = Object.keys(route.query)
      .filter((key) => !excludedQueryKeys.includes(key))
      .reduce((acc: Record<string, any>, key) => {
        acc[key] = route.query[key]
        return acc
      }, {})
    // console.log('filteredQuery:', filteredQuery)

    const valuesObj = getValuesByCustomKeys(context, pathsWithKeys)
    // console.log('valuesObj:', valuesObj)

    const combinedParams = { ...filteredQuery, ...valuesObj }
    // console.log('combinedParams:', combinedParams)
    // console.log('previousParams:', previousParams)
    // console.log('change:', paramsChanged(previousParams, combinedParams))

    if (paramsChanged(previousParams, combinedParams)) {
      // 如果参数有变化，执行 fetchData 并更新 previousParams
      fetchData(combinedParams)
      Object.assign(previousParams, combinedParams) // 更新 previousParams 为最新的参数
    }
  })
}
